﻿Option Infer On
Imports Core
Imports System.IO
Imports System.Xml
Imports Feed.Storage
Imports Feed.Database
Imports System.Diagnostics
Imports Microsoft.VisualBasic.Compatibility.VB6
Namespace Base
    Public Class FeedBase
        Dim feedTitle, feedlink, currFeedGuid As String
        ' Dim Items As ICollection(Of Storage.FeedItem) = New Collections.Generic.List(Of Storage.FeedItem)
        Public Enum Formats
            RSS
            Atom
            RDF
        End Enum
        Public Sub GetFeedXml(ByVal filename As String)
            If IO.File.Exists(filename & ".xml") Then ParseFeed(New XmlTextReader(New IO.FileStream(API.ReturnCachePath() & filename & ".xml", FileMode.Open)), filename)
        End Sub
        Public Sub GetFeedXML(ByVal url As Uri, ByVal IsNewFeed As Boolean, ByVal item As FeedDBItem)
            Dim NetReq = New Base.NetRequest
            Dim FeedFileName As String = System.Guid.NewGuid().ToString
            Dim xml = NetReq.GetFromWeb(url, False)
            If IsNewFeed = False Then
                If IO.File.Exists(item.Guid & ".xml") Then Kill(API.ReturnCachePath() & item.Guid & ".xml")
                SaveToCache(xml, item.Guid)
                ParseFeed(New XmlTextReader(New IO.FileStream(API.ReturnCachePath() & item.Guid & ".xml", FileMode.Open, FileAccess.Read)), item.Guid)
            Else
                SaveToCache(xml, FeedFileName)
                ParseFeed(New XmlTextReader(New IO.FileStream(API.ReturnCachePath() & FeedFileName & ".xml", FileMode.Open)), FeedFileName)
            End If
        End Sub
        Private Sub SaveToCache(ByVal Stream As IO.Stream, ByVal FileName As String)
            Dim text3 As String = ""
            Dim Stream1 As Stream = Stream
            Dim reader1 As New StreamReader(Stream1, True)
            text3 = reader1.ReadToEnd
            Stream1.Close()
            reader1.Close()
            My.Computer.FileSystem.WriteAllText(API.ReturnCachePath() & FileName & ".xml", text3, False)
        End Sub
        Private Sub ParseFeed(ByVal reader As XmlReader, ByVal guid As String)
            Dim elementNames As Object() = ReturnNameTable(reader.NameTable)
            reader.MoveToContent()
            Dim syndFormat As Formats
            Dim name = reader.LocalName
            If name.Equals(elementNames(rss).ToString) Then
                syndFormat = Formats.RSS
                currFeedGuid = guid
                ProcessFeed(reader, elementNames)
                '  Return Items
            End If
        End Sub
        ''TODO: ProcessImgTag
        Private Function ProcessImgTag(ByVal reader As XmlReader) As String()
            reader.Skip()
            Return Nothing
        End Function
        ''TODO: Save Feed Info
        Private Sub ProcessFeed(ByRef reader As XmlReader, ByVal elementNames As Object())
            Dim name = reader.LocalName
            Do Until reader.EOF = True
                reader.Read()
                If reader.NodeType <> XmlNodeType.Element Then Continue Do
                name = reader.LocalName
                If name.Equals(elementNames(description).ToString) Then Debug.Print(reader.ReadElementString("description"))
                If name.Equals(elementNames(image).ToString) Then ProcessImgTag(reader)
                If name.Equals(elementNames(title).ToString) Then feedTitle = reader.ReadElementString("title")
                If name.Equals(elementNames(link).ToString) Then feedlink = reader.ReadElementString("link")
                If name.Equals(elementNames(item).ToString) Then
                    Dim item As Storage.FeedItem = ProcessItem(reader, Formats.RSS, elementNames)
                    If IsItemNothing(item) = False Then
                        item.FeedName = feedTitle
                        item.Guid = GetGuidFromFeedTitle(feedTitle)
                        If IsDupe(item.Title) = False Then
                            [Global].Items.Add(item)
                            reader.Skip()
                        Else
                            reader.Skip()
                        End If
                    End If
                End If
            Loop
            reader.Close()
        End Sub
        Private Function GetGuidFromFeedTitle(ByVal FeedTitle As String) As String
            For Each item As Database.FeedDBItem In [Global].Feeds
                If item.Title = FeedTitle Then Return item.Guid
            Next
            Return currFeedGuid 'System.Guid.NewGuid()
        End Function
        Private Function IsDupe(ByVal itemTitle As String)
            For Each item As FeedItem In [Global].Items
                If item.Title = itemTitle Then Return True
            Next
            Return False
        End Function
        Protected Function ProcessItem(ByRef reader As XmlReader, ByVal format As Formats, ByVal elementNames As Object()) As FeedItem
            Dim titlevar As String = ""
            Dim URLvar As String = ""
            Dim authorvar As String = ""
            Dim bodyvar As String = ""
            Dim subjvar As String = ""
            Dim pubDate As Date = Nothing
            Dim categories As String() = Nothing
            Dim feedItem As Storage.FeedItem = Nothing
            Dim endOfNode As Boolean
            Dim name As Object
            While (endOfNode OrElse reader.Read())
                If reader.NodeType <> XmlNodeType.Element Then Continue While
                name = reader.LocalName
                endOfNode = False
                If reader.NodeType = XmlNodeType.Whitespace Then reader.MoveToContent()
                If IsNothing(feedItem) Then feedItem = New Storage.FeedItem
                If reader.NodeType = XmlNodeType.EndElement Then
                    If name.Equals(elementNames(item).ToString) Then endOfNode = True
                End If
                If name.Equals(elementNames(content).ToString) Then bodyvar = reader.ReadElementString("content")
                If name.Equals(elementNames(title).ToString) Then titlevar = reader.ReadElementString("title")
                If name.Equals(elementNames(itemdate).ToString) Then pubDate = reader.ReadElementContentAsDateTime()
                If name.Equals(elementNames(category).ToString) Then ProcessCategories(reader)
                If name.Equals(elementNames(author).ToString) Then authorvar = reader.ReadElementString("author")
                If name.Equals(elementNames(description).ToString) Then bodyvar = reader.ReadElementString("description")
                If name.Equals(elementNames(link).ToString) Then URLvar = reader.ReadElementString("link")
                If name.Equals(elementNames(subject).ToString) Then subjvar = reader.ReadElementString("subject")
                feedItem.Author = authorvar
                feedItem.Content = bodyvar
                feedItem.Link = URLvar
                feedItem.Title = titlevar
                feedItem.pubDate = pubDate
                feedItem.subject = subjvar
                If IsItemNothing(feedItem) = False Then
                    Return feedItem
                End If
            End While
            Return Nothing
        End Function
        Private Function IsItemNothing(ByVal fi As FeedItem) As Boolean
            Try
                If Not fi.Title = "" And Not fi.Link = "" And Not fi.Content = "" And Not fi.pubDate.ToString = "#12:00:00 AM#" Then Return False
                Return True
            Catch Ex As Exception
                Return True
            End Try
        End Function
        ''TODO: Process Categories
        Private Function ProcessCategories(ByRef reader As XmlReader) As String()
            reader.Skip()
            Return Nothing
        End Function

    End Class
End Namespace